package com.xincheng.shuimalong.util;

import android.util.Log;

import com.google.gson.Gson;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.api.RetroFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaote on 2017/6/19.
 */

public class GsonUtil {
    public static <T> T parseData(Object data, Class<T> clazz) {
        Gson gson = RetroFactory.buildGson();
        String jsonStr = gson.toJson(data);
        if (isEmptyJson(jsonStr)) {
            return null;
        }
        return gson.fromJson(jsonStr, clazz);
    }

    public static <T> List<T> parseData(Object data, Type type) throws Exception {
        Gson gson = RetroFactory.buildGson();
        String jsonStr = gson.toJson(data);
        if(isEmptyJson(jsonStr)) {
            return null;
        }
        List<T> list = gson.fromJson(gson.toJson(data), type);
        return list;
    }

    public static <T> List<T> parseData(String jsonStr, Type type) {
        if (isEmptyJson(jsonStr)) {
            return null;
        }
        Gson gson = RetroFactory.buildGson();
        List<T> list = gson.fromJson(jsonStr, type);
        return list;
    }

    public static <T> T parseData(String jsonStr, Class<T> clazz) {
        if (isEmptyJson(jsonStr)) {
            return null;
        }
        Gson gson = RetroFactory.buildGson();
        T t = gson.fromJson(jsonStr, clazz);
        return t;
    }

    public static <T> String toJson(T t) {
        Gson gson = RetroFactory.buildGson();
        return gson.toJson(t);
    }

    public static <T> String toJson(List<T> t, Type type) {
        Gson gson = RetroFactory.buildGson();
        return gson.toJson(t, type);
    }

    private static boolean isEmptyJson(String jsonStr) {
        if (CommonUtil.isEmpty(jsonStr)) {
            return true;
        }
        switch (jsonStr) {
            case "[]":
            case "{}":
            case "null":
            case "false":
                return true;
        }
        return false;
    }

}
